package com.java.jvalidator.framework;

import java.util.HashSet;
import java.util.Set;

import com.java.jvalidator.framework.config.Parameters;
import com.java.jvalidator.framework.config.ValidationConfig;

public class ValidationFacade {
	// ValidationConfig
	private ValidationConfig globalConfig = ValidationConfig.getInstance();
	private static ValidationFacade instance;
	private Set<Object> session;

	private ValidationFacade() {

	}

	// 单例 singleton
	public static ValidationFacade getInstance() {
		if (instance == null) {
			synchronized (ValidationFacade.class) {
				if (instance == null) {
					instance = new ValidationFacade();
				}
			}
		}
		return instance;
	}

	/**
	 * 
	 * @param target
	 *            需要被校验的对象
	 * @return ValidationResult 校验结果对象
	 * @throws ValidationException
	 */
	public ValidationResult validate(Object target) throws ValidationException {
		return validate(target, null);
	}

	/**
	 * 
	 * @param target
	 *            需要被校验的对象
	 * @param propertyPattern
	 *            需要被校验的对象的字段名pattern(例如，check对象内所有以“a”开头的字段)
	 * @return ValidationResult 校验结果对象
	 * @throws ValidationException
	 */
	public synchronized ValidationResult validate(Object target, String propertyPattern) throws ValidationException {
		if (target == null) {
			throw new ValidationException(ValidationExceptionMsg.VALIDATION_TARGET_NULL_ERROR);
		}
		this.session = new HashSet<Object>();
		this.session.add(target);
		ValidationResult result = this.globalConfig.validate(target, propertyPattern);
		this.session.clear();
		return result;
	}

	public ValidationResult validateInSession(Object target) throws ValidationException {
		if (target == null) {
			return null;
		}
		if (this.session.contains(target)) {
			return null;
		}
		this.session.add(target);
		return this.globalConfig.validate(target, null);
	}

	public void configCustomValidator(Object target, String propertyName, Class<?> customValidatorClass, Parameters params) throws ValidationException {
		if ((target == null) || (propertyName == null) || (customValidatorClass == null) || (params == null)) {
			throw new ValidationException(ValidationExceptionMsg.CUSTOM_VALIDATOR_CONFIG_ERROR);
		}
		this.globalConfig.configValidator(target.getClass().getName(), propertyName, customValidatorClass.getName(), params);
	}

	public void setPlaceHolderValues(Object target, String propertyName, String errorMsgName, String[] strings) throws ValidationException {
		if ((target == null) || (propertyName == null) || (errorMsgName == null)) {
			return;
		}
		this.globalConfig.setPlaceHolderValue(target.getClass(), propertyName, errorMsgName, strings);
	}
}
